package com.yunhe.policyfulfillment.authority.controller;

import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.utils.AliOssApiUtils;
import com.yunhe.policyfulfillment.authority.service.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @ClassName FileUploadController
 * @Description TODO
 * @Author HeTao
 * @Date 2021/7/22 17:31
 * @Version 1.0
 **/
@Api(value = "FileUpload", description = "文件上传", tags = {"Model_File_Upload"})
@RestController
@RequestMapping(value = "/files")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 文件上传
     */
    @PostMapping(value = "/uploadFile")
    @ApiOperation(value = "文件上传")
    public ResponseEntity<ResultObject<String>> uploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception {
        //String url = AliOssApiUtils.putObjectByte(file);
        String url = fileUploadService.uploadFile(file);
        StringBuffer requestURL = request.getRequestURL();
        String urlStr = requestURL.substring(0, requestURL.lastIndexOf("files")) + "files/getFile?filePath=" + url;
        return new ResponseEntity<>(new ResultObject<>(urlStr), HttpStatus.OK);
    }

    public static void main(String[] args) {
        String url  = "http://47.108.95.221:6129/policyOrg/findPolicyOrgs";
        System.out.println(url.substring(0,url.lastIndexOf("policyOrg")));
    }

    @RequestMapping(value = "/getFile",method = RequestMethod.GET)
    @ApiOperation(value = "文件流获取（下载）")
    public ResponseEntity<ResultObject> getFile(HttpServletRequest request,
                                                HttpServletResponse response,
                                                @RequestParam("filePath") String filePath) throws IOException, ArgumentErrorException {
        fileUploadService.getFile(filePath,response,request);
        return null;
    }


    /**
     * 文件删除
     */
    @PostMapping(value = "/deleteFile")
    @ApiOperation(value = "文件删除")
    public ResponseEntity<ResultObject<Void>> deleteFile(@RequestParam("url") String url) throws IOException, ArgumentErrorException {
        fileUploadService.deleteFile(url);
        return new ResponseEntity<>(new ResultObject(), HttpStatus.OK);
    }
}
